import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';

import 'FriendList.dart';

class FriendSearch extends StatefulWidget {
  String searchKey = "";

  FriendSearch({required this.searchKey});

  @override
  State<StatefulWidget> createState() {
    return _FriendSearch();
  }
}

class _FriendSearch extends State<FriendSearch> {
  TextEditingController controller = TextEditingController();
  dynamic user;

  @override
  void initState() {
    controller.text = widget.searchKey;
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      searchUser(widget.searchKey);
    });
    super.initState();
  }

  searchUser(String userId) {
    if (userId.isEmpty) return;
    HttpGo(context).get("/Member/GetUserName?userId=$userId", {}, (data) {
      user = data;
      setState(() {});
    }, (code, error) => showToast(error));
  }

  SendInvite() {
    HttpGo(context).post("/Profile/AddRelationship", {"studentId": Global.studentId, "addUserId": user["userId"]}, (data) {
      showToast("已發出交友申請");
      PageUtil().back(context);
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return MyPage(
        "朋友圈",
        SingleChildScrollView(
            child: Container(
                padding: EdgeInsets.all(16),
                child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Container(
                      decoration: Global.getBg(MyColor.F2, 5),
                      padding: EdgeInsets.fromLTRB(4, 0, 8, 0),
                      margin: EdgeInsets.fromLTRB(0, 8, 0, 24),
                      height: 28,
                      child: Row(children: [
                        Expanded(child: NormalInput(hintText: "User ID", fontSize: 12, controller: controller, onSubmit: searchUser)),
                        LocalImage("search_blue.png", width: 16, onTap: () {
                          searchUser(controller.text);
                        })
                      ])),
                  Visibility(visible: user != null, child: ItemFriend(user, showInvite: true, onInviteTap: SendInvite))

                  // ListView.builder(
                  //     itemCount: 7,
                  //     shrinkWrap: true,
                  //     physics: NeverScrollableScrollPhysics(),
                  //     itemBuilder: (BuildContext context, int index) {
                  //       return ItemFriend(null, showInvite: true, onInviteTap: SendInvite);
                  //     })
                ]))));
  }
}
